package org.activemonitoring.datastore.rest;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.activemonitoring.datastore.dao.DataStoreDao;
import org.activemonitoring.datastore.rest.client.DataStoreRestClient;
import org.activemonitoring.domain.Measure;
import org.activemonitoring.domain.Measures;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sun.grizzly.http.SelectorThread;
import com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory;

import static org.junit.Assert.assertEquals;

public class DataStoreRestClientCase {

    private static ClassPathXmlApplicationContext applicationContext;
    private static DataStoreRestClient dataStoreRestClient;
    private static SelectorThread threadSelector;
    private static DataStoreDao dataStoreDao;

    @BeforeClass
    public static void setUp() throws Exception {
        final String baseUri = "http://localhost:9998/active-monitoring-store/services/";
        final Map<String, String> initParams = new HashMap<String, String>();
        initParams.put("com.sun.jersey.config.property.resourceConfigClass",
                "com.sun.jersey.api.core.PackagesResourceConfig");
        initParams.put("com.sun.jersey.config.property.packages", "org.activemonitoring.datastore.rest");
        threadSelector = GrizzlyWebContainerFactory.create(baseUri, initParams);

        applicationContext = new ClassPathXmlApplicationContext(new String[] { "applicationContext-harvesters.xml",
                "applicationContext-datastore.xml", "applicationContext-test-rest.xml" });
        applicationContext.start();
        dataStoreDao = applicationContext.getBean("dataStoreDao", DataStoreDao.class);
        dataStoreRestClient = applicationContext.getBean("dataStoreRestClient", DataStoreRestClient.class);
        dataStoreRestClient.setDatastoreUrl(baseUri + "datastore");
    }

    @Test
    public void testDataStorePing() throws Exception {
        boolean pingResult = dataStoreRestClient.ping();
        assertEquals(true, pingResult);
    }

    @Test
    public void testClientPostMeasure() throws Exception {
        Measure measure = new Measure();
        measure.setModuleName("Test");
        measure.setName("testClientPostMeasure");
        measure.setCorrelationId("Test-987654321-123456789");
        long time = new Date().getTime();
        measure.setStartTime(time - 1000L);
        measure.setEndTime(time);
        Measures measures = new Measures();
        measures.getMeasure().add(measure);

        dataStoreRestClient.store(measures);
        assertEquals(1, dataStoreDao.getMeasures().size());
    }

    @AfterClass
    public static void tearDown() {
        dataStoreDao.clear();
        applicationContext.stop();
        threadSelector.stopEndpoint();
    }
}
